#!/usr/bin/env bash

[ ! -z "$_E" ] && {
    set -e 
}

#set -o errtrace

#cd "$(dirname "$0")"
[ "${_XT:-}" ] && {
    set -o xtrace
}
[ "${_PF:-}" ] && {
    set -o pipefail
}
[ "${_NC:-}" ] && {
    #overwrite file
    set -o noclobber
}



# * match .
#shopt -s dotglob  

#bash comments
: '
bash
multiline 
comment
'


MY_Z_PATH=$HOME/.z
BASE_GIT_URL=https://gitee.com/ifa6/ii/raw/i

DATE(){
    echo $(date '+%Y%m%d')
}
DATE_HOUR(){
    echo $(date '+%Y%m%d%H')
}
DATE_MIN(){
    echo $(date '+%Y%m%d%H%M')
}
DATE_SEC(){
    echo $(date '+%Y-%m-%d %H:%M:%S')
}
TIME(){
    echo $(date '+%H%M%S')
}
_info() {
    echo -e "\e[32m$(DATE_SEC) $@\e[39m"
}
_warn() {
    echo -e "\e[93m$(DATE_SEC) $@\e[39m"
}
_err() {
    echo -e "\e[31m$(DATE_SEC) $@\e[39m"
}
_i() {
    echo -e "\e[32m$@\e[39m"
}
_w() {
    echo -e "\e[93m$@\e[39m"
}
_e() {
    echo -e "\e[31m$@\e[39m"
}
trapErr() {
    _info "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}
#trap trapErr ERR
[ -f $HOME/my/vault/setting.ini ] && . $HOME/my/vault/setting.ini
declare -A usage

sysEnvPath=$HOME/my/data/bashenv
userEnv=$HOME/myconfig
appEnv=""
envArr=("$sysEnvPath" "$userEnv" "$appEnv")
[[ -z $ENV_IMPORT_FLAG_1 ]] && {
    #环境变量
    for env in ${envArr[@]};do
    [  -f "$env" ] && echo $env && . $env
    done
}
usage[iwp]="安装python的web.py框架"
usage[swp]="启动python的web.py服务 1.port"
usage[lp]="列出打开的端口"
usage[fb]="查找大文件,确定要删除的文件"

lp(){
    #lsof -iTCP -sTCP:LISTEN -n -P
    netstat -lntp
}
fb(){
    _info "查找大文件,确定要删除的文件:"
    lsof -F sn0 | tr -d '\000' | grep deleted | sed 's/^[a-z]*\([0-9]*\)n/\1 /' | sort -n
    _info "查找删除的，未释放空间的大文件"
    lsof +L1
    _info "选择上一要释放空间的进程的pid和fd,执行下面命令"
    echo 'echo "" > /proc/$pid/fd/$fd'

}

usage[pb]="端口转发1.from 2.toHost 3.toPort"
pb(){
    socat TCP-LISTEN:$from,fork,reuseaddr  TCP:$toIp:$toPort
}
swp(){
    local port=${1:-7001}
    cd $MY_Z_PATH/web && python $MY_Z_PATH/web/main.py $port &
    _info "start python web at 7001"
    _warn "如果提示Module_six_moves_urllib_parse' object has no attribute 'unquote_to_bytes'"
    _info "执行 pip uninstall cheroot"
    _info "执行 pip install --force-reinstall cheroot==6.5.4"
    _info "start access"
    sleep 0.3
    curl --max-redirs 3 http://localhost:$port/
}
iwp(){
    ies inst_pyweb.sh
    [ ! -d $MY_Z_PATH/web ] && mkdir $MY_Z_PATH/web
    inst_pyweb.sh
}


usage[_h]="脚本功能介绍"
_h(){
    cat -<<E

_XT: 跟踪脚本
_PF: pipe错误也退出
_NC: noclobber 覆盖文件

E

}
#fan mou qiang 
_isFqOk(){
    if ping -t 1  -c 1 google.com; then
        echo "Fan mou qiang failed"
    fi
}
_isNetOk(){
    if ping -t 1  -c 1 www.baidu.com; then
        echo "net ok"
    fi
}

_cc(){
   
    _info "copy $0 content to clipboard"
    local tmp=/tmp/$RANDOM.cc
    cp $0 $tmp
    local hasHeaderTemp="$(grep "source *sh_temp_header.sh" $tmp)"
    if [ ! -z "$hasHeaderTemp" ];then
    sed -i.bk  "/sh_temp_header.sh/{
    s/source[[:space:]]*sh_temp_header.sh//
    r $MY_SCRIPT/sh_temp_header.sh
}" $tmp
fi
         
 
    local hasShTemp="$(grep "source *sh_temp.sh" $tmp)"


    sed -i.bk  "/sh_temp.sh/{
    /source[[:space:]]*sh_temp.sh/d
}" $tmp

    [ ! -z "$hasShTemp" ] && {
        cat $MY_SCRIPT/sh_temp.sh >> $tmp
    }
    
    #sed -ibak "s/sh_temp.sh/$temp/" /tmp/$RANDOM.cc
    cat $tmp|pbcopy
    _info "replaced file $tmp"

}
usage[ies]="安装额外脚本 1.script"
ies(){
    local script=$1
    [ -z "$script"  ] && _err "${usage[ies]}" && return
    
    [ ! -d "$MY_Z_PATH/bin" ] && mkdir -p $MY_Z_PATH/{bin,web}
    [ -z "$script" ] && _err "empty script $script" && return
    curl -S -s $BASE_GIT_URL/shell/$script -o $script
    if [ $? -eq 0 -a  ! -z "$script" -a  -f $script ];then
    
     mv -f $script $MY_Z_PATH/bin/$script  && chmod +x $MY_Z_PATH/bin/$script 
      _info "安装脚本成功 $script"
    else 
        _err "安装脚本失败 $script"
     fi
    
}
h(){
    cat -<<EOF
socat 
TCP:LOCALHOST:8111 EXEC:bash
TCP-LISTEN:8111,fork,reuseaddr
websocketd
socat TCP-LISTEN:23,reuseaddr,fork,crlf exec:/bin/login,pty,setsid,setpgid,stderr,ctty
服务端:socat TCP-LISTEN:8082,fork,reuseaddr  EXEC:/usr/bin/bash,pty,stderr
客户端: socat file:`tty`,raw,echo=0 TCP:localhost:8082  
#文件传输
socat -u TCP-LISTEN:8080 open:record.log,create    # 服务端接收文件
socat -u open:record.log TCP:localhost:8080 
# 端口代理
socat TCP-LISTEN:<本地端口>,reuseaddr,fork SOCKS:<代理服务器IP>:<远程地址>:<远程端口>,socksport=<代理服务器端口>
socat TCP-LISTEN:<本地端口>,reuseaddr,fork PROXY:<代理服务器IP>:<远程地址>:<远程端口>,proxyport=<代理服务器端口>
EOF
    
}
_ht(){
   local port=${1:-1999}
   [  -z "$(which nc)" ] && echo "pls install nc first" && return
#     local response="$@"
# local chunckedResp=$(cat - <<EOF
# HTTP/1.1 200 OK
# Content-Type: text/plain
# Transfer-Encoding: chunked


# 100
# $response
# 0


# EOF
# )
# local plainResp=$(cat - <<EOF1
# HTTP/1.1 200 OK
# Content-Type: text/html

# $response

# EOF1

# )
   _i "listen at $port,test with http://localhost:$port/http_test"
  while true ;
do
   #use read line from pipe to make it blocks before request comes in,
   #this is the key.
   { read line<pipe;echo -e "HTTP/1.1 200 OK\r\n";action=$(echo "$line"|awk '{print $2}'|tr -d '/');$action;
   }  | nc  -D -l   $port > pipe;

done

}
#script begin
desc="linux toolSuite"
#[cmd]="cmd description"
usage[i]="init shell"
usage[iex]="安装额外的包"
usage[iba]="安装基础包"
instFdRg(){
    tar xvzf ripgrep-13.0.0-x86_64-unknown-linux-musl.tar.gz -C /usr/local
    tar xvzf fd-v8.5.2-x86_64-unknown-linux-musl.tar.gz -C /usr/local
    ln -f -s /usr/local/fd-*/fd /usr/bin
    echo "source $(ls /usr/local/rip*/complete/rg.bash)" >> $HOME/.bash_profile 
    ln -f -s /usr/local/ripgrep-*/rg /usr/bin
    iba
}
iex(){
     yum install tcpdump
}
iba(){
    yum install sysstat lsof tcpdump
}

editRepo(){
    sed 's/\:\/\/[A-Za-z0-9_.-]*/\:\/\/mirrors\.aliyun\.com/' /etc/yum.repos.d/CentOS-Base.repo
    yum update
}
iPipRepo(){
  local confDir=$HOME/.pip
  [ ! -d $confDir ]  && mkdir $confDir
  cat ->$confDir/pip.conf <<EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
EOF

}
i(){
    [ ! -d $MY_Z_PATH ] && mkdir -p $MY_Z_PATH/{bin,web,pkgs}
    echo "export MY_Z_PATH=~/.z">>$HOME/.bash_profile
    echo "export PATH=$PATH:$MY_Z_PATH/bin">>/etc/profile
    echo "export PATH=$PATH:$MY_Z_PATH/bin">>$HOME/.bash_profile
    . $HOME/.bash_profile
    local tkUrl="${1:-"$LI_TK_URL"}"
    [ -z "$tkUrl" ] && _err "empty $tkUrl" && return
    local pkgDir=$MY_Z_PATH/.pkgs
    [ ! -d "$pkgDir" ] && mkdir -p $pkgDir
    cd $pkgDir
    curl $LI_TK_URL -o $pkgDir/file.tar
    tar xvf file.tar
    #安装fd,rg
    instFdRg
    _info "编辑yum repo为阿里云"
    if [ -z "$(grep -r mirrors.aliyun.com /etc/yum.repos.d)" ];then
     editRepo
    fi

}
usage[cmd]="显示进程的信息"
usage[b64]="b64编码"
usage[d64]="b64解码"

usage[upd]="update r"

upd(){
    curl -S -s $BASE_GIT_URL/r -o /usr/bin/r    
}
b64(){

    echo -n "$1"|openssl base64
}
d64(){
    echo  "$1"|openssl base64 -d
}
cmd(){
 local proc="$1"
 [ -z "$proc" ] && _err "empty proc $proc" && return
 local pid=$(ps -ef|grep "$proc"|awk '{print $2}'|grep -v 'grep '|head -1)
 [ ! -z "$pid" ] && {
  ps -eo pid,etime,args,time|grep nginx
  echo "PWD: $(ls -l /proc/$pid/cwd)"
  echo "Exe: $(ls -l /proc/$pid/exe)"
 }
}
usage[hs]="start http server 9999"
hs(){
    python -m SimpleHTTPServer ${1:-9999}
}

func=$1
isHelp=$2
MY_DIR=$HOME/my
usage['_']="search usage"
usage['__']="search script content"
usage['_pc']="print script content"
usage["_r"]="show in finder"
usage["_v"]="open in vs code"
usage["_s"]="open in sublime"
usage["_cp"]="copy current script path"
usage["_cc"]="copy current script content"
usage["_sr"]="查看源代码 1.file 2.func"
_pc(){
    bat $0
}
_(){
 rg "usage\[.*proxy" $0
}
__(){
 rg "$@" $0 
}
_cp(){
    echo "$0"|pbcopy
}
_cc(){
    pbcopy < "$0"
}
_sr(){

     local func=$1
     rg --multiline --multiline-dotall  -e  "$func\(\)\{.*?\n}\n" $0
}
_c(){
    _info "copy $0 to clipboard"
    echo $0|pbcopy
}
_r(){
    open $MY_DIR/data/script
}

_v(){
    local editor="vim"
    [ ! -z "$(which subl)" ] && editor="subl"
    [ ! -z "$(which code)" ] && editor="code"
    $editor $MY_DIR/data/script
}
readonly URI_REGEX='^(([^:/?#]+):)?(//((([^:/?#]+)@)?([^:/?#]+)(:([0-9]+))?))?(/([^?#]*))(\?([^#]*))?(#(.*))?'
#                    ↑↑            ↑  ↑↑↑            ↑         ↑ ↑            ↑ ↑        ↑  ↑        ↑ ↑
#                    |2 scheme     |  ||6 userinfo   7 host    | 9 port       | 11 rpath |  13 query | 15 fragment
#                    1 scheme:     |  |5 userinfo@             8 :…           10 path    12 ?…       14 #…
#                                  |  4 authority
#                                  3 //…

parse_scheme () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[2]}"
}

parse_authority () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[4]}"
}

parse_user () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[6]}"
}

parse_host () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[7]}"
}

parse_port () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[9]}"
}

parse_path () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[10]}"
}

parse_rpath () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[11]}"
}

parse_query () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[13]}"
}

parse_fragment () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[15]}"
}
fn_exists() {
    declare -f -F $1 > /dev/null
    echo $?
}

ec(){
   local port=${1:-1999}

#     local response="$@"
# local chunckedResp=$(cat - <<EOF
# HTTP/1.1 200 OK
# Content-Type: text/plain
# Transfer-Encoding: chunked


# 100
# $response
# 0


# EOF
# )
# local plainResp=$(cat - <<EOF1
# HTTP/1.1 200 OK
# Content-Type: text/html

# $response

# EOF1

# )
   _info "listen at $port,test with http://localhost:$port/http_test"
  while true ;
do
   #use read line from pipe to make it blocks before request comes in,
   #this is the key.
   { 
       set -x 
       read line<pipe;echo -e "HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\n"; \
       action=$(echo "$line"|awk '{print $2}'|tr -d '/'); \
       if [  "$(fn_exists $action)" != "0"  -o -z "$action" ];then echo -e "404 error";else  $action;fi
   }  | nc  -D -l   $port > pipe;
   set +x

done

}

    if [ "$func" = "-" -o -z "$func" ];then
[ ! -z "$desc" ] && _i "$desc\n"
echo -e "$(_i usage):\n"
for key in "${!usage[@]}";do
    echo -e "$(_i $key): \n\t${usage[$key]}"
done

else


if [ "$(type -t $func)" = "function" ];then 

    shift 
    if [ "$isHelp" = "-" ];then 
        #usage="${func}_usage"
        #echo -e "$func usage:\n ${!usage}"
        echo "获取某个的选项帮助 script \$option -"
        echo -e "$(_i usage:\\n$func)\n  ${usage[$func]}"
        
    else
       $func "$@"
    fi
else 
 _err "$func not found" 
fi

fi

